<?php


namespace app\api\controller\v33;


use app\api\controller\v2\Auth;
use app\common\cachemodel\zl1_relation\Zl1IdeaTag;
use app\common\cachemodel\zl1_relation\Zl1RelationAnalysisIdea;
use app\common\cachemodel\zl1_relation\Zl1RelationAnalysisIdeaRecodeInfo;
use app\common\cachemodel\zl1_relation\Zl1RelationAnalysisIdeaSubmitCase;
use app\common\lib\SensorsData;
use app\common\lib\Util;

class UserRelationAnalysis extends Auth
{
    /**
     *  提交方案
     */
    public function submitCase()
    {
        $tagInfoStr = input('tag_info/s', '');
        $rids = input('rids/s', '');

        $tagInfoList = json_decode($tagInfoStr, true);
        $ridArr = explode(',', $rids);

        if (!isset($tagInfoList[1], $tagInfoList[2], $tagInfoList[3], $tagInfoList[4], $tagInfoList[5], $tagInfoList[6], $tagInfoList[7]) || empty($ridArr))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $ideaTagModel = new Zl1IdeaTag();
        $tagNames = [];
        foreach ($tagInfoList as $type => $tagId)
        {
            $tagInfo = $ideaTagModel->getInfoById($tagId);

            if ($tagInfo['type'] !== $type)
            {
                return show(config('code.error'), '请求异常，请稍后再试～');
            }
            $tagNames[] = $tagInfo['name'];
        }

        $recodeModel = new \app\common\cachemodel\Recode();
        foreach ($ridArr as $ridItem)
        {
            $recode = $recodeModel->getInfoById($ridItem);
            if (!$recode || $recode['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '选择的档案不存在');
            }

            // if ((int)$recode['isself'] === 1)
            // {
            //     return show(config('code.error'), '不能选择自己的档案');
            // }
        }

        // 提交方案入库
        (new Zl1RelationAnalysisIdeaSubmitCase())->saveCaseInfo([
            'uid' => $this->user['id'],
            'rids' => $rids,
            'tag_info' => $tagInfoStr,
            'create_time' => $this->request->time()
        ]);

        $unLockCaseData = (new Zl1RelationAnalysisIdea())->getUnlockCaseList($this->user['id']);

        $caseTagInfo = sprintf("%d:%d:%d:%d:%d:%d:%d", $tagInfoList[1], $tagInfoList[2], $tagInfoList[3], $tagInfoList[4], $tagInfoList[5], $tagInfoList[6], $tagInfoList[7]);

        //  你的理想型提交购买    IdealLoverBuy    打点
        SensorsData::track($this->user['id'], true, 'IdealLoverBuy', [
            'tag_list' => $tagNames,    // 入口名称
            'record_num' => count($ridArr),    // 新增后数量
        ]);

        return show(config('code.success'), '请求成功', [
            'status' => in_array($caseTagInfo, $unLockCaseData, true) ? 2 : 1,  //  判断是否解锁过相同的方案
        ]);
    }

    /**
     * 获取我的理想型 方案列表
     */
    public function getMyIdeaCaseList()
    {
        $pageData = (new Zl1RelationAnalysisIdea())->getListPage($this->user['id'], 'id', ['status', 'create_time', 'tag_info', 'id']);

        $dataList = [];
        $num = $pageData['total'];
        $num = $num - $pageData['per_page'] * ($pageData['current_page'] - 1);
        $tagList = [];
        $ideaTagModel = new Zl1IdeaTag();
        foreach ($pageData['data'] as $pageDatum)
        {
            $tags = [];
            ksort($pageDatum['tag_info']);
            foreach ($pageDatum['tag_info'] as $tagId)
            {
                if (isset($tagList[$tagId]))
                {
                    $tags[] = $tagList[$tagId];
                } else
                {
                    $tagInfo = $ideaTagModel->getInfoById($tagId, ['id', 'name']);
                    $tagList[$tagInfo['id']] = $tagInfo['name'];

                    $tags[] = $tagInfo['name'];
                }
            }

            if ($pageDatum['status'] === 3)
            {
                $status = 1;
            } elseif ($pageDatum['status'] === 4)
            {
                $status = 3;
            } else
            {
                $status = $pageDatum['status'];
            }

            $dataList[] = [
                'id' => $pageDatum['id'],
                'title' => '方案' . $num,
                'status' => $status,
                'create_time' => date('Y.m.d H:i', $pageDatum['create_time']),
                'tags' => $tags,
            ];

            $num--;
        }

        $pageData['data'] = $dataList;

        return show(config('code.success'), '请求成功', $pageData);
    }

    /**
     * 我的理想型 方案详情
     */
    public function getMyIdeaCaseDetail()
    {
        $id = input('id/d', 0);

        if (!$id)
        {
            return show(config('code.error'), '请求异常');
        }

        $caseDetail = (new Zl1RelationAnalysisIdea())->getInfoById($id);

        if (!$caseDetail || $caseDetail['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '方案不存在～');
        }

        $tagIds = array_values($caseDetail['tag_info']);

        $tagInfo = (new Zl1IdeaTag())->batchGetInfoByIds($tagIds, ['id', 'name', 'type']);
        // 获取档案信息
        $recodeInfoList = (new Zl1RelationAnalysisIdeaRecodeInfo())->getInfoById($id, ['recode_info']);
        $utilModel = new Util();
        $dataList = [];
        $tName = [
            1 => '外貌',
            2 => '性格',
            3 => '表达',
            4 => '事业',
            5 => '财富',
            6 => '恋爱',
            7 => '人际',
        ];
        foreach ($caseDetail['content'] as $resultItem)
        {
            $recodeDetails = $recodeInfoList['recode_info'][$resultItem['rid']];

            if ($recodeDetails['timezone'])
            {
                if ($recodeDetails['timezone'] > 0)
                {
                    $timezone = '东' . $utilModel->numberChinese($recodeDetails['timezone']) . '区 GMT+' . $recodeDetails['timezone'];
                } else
                {
                    $timezone = '西' . $utilModel->numberChinese(abs($recodeDetails['timezone'])) . '区 GMT' . $recodeDetails['timezone'];
                }
            } else
            {
                $timezone = '中时区 GMT0';
            }

            $longLat = ($recodeDetails['ew'] == 1 ? 'E' : 'W') . "{$recodeDetails['long_deg']}°{$recodeDetails['long_min']}′ " . ($recodeDetails['ns'] == 1 ? 'N' : 'S') . "{$recodeDetails['lat_deg']}°{$recodeDetails['lat_min']}′";

            $infoList = [];
            foreach ($resultItem['result'] as $item)
            {
                $infoList[] = [
                    'type' => $tagInfo[$item['id']]['type'],
                    'name' => $tName[$tagInfo[$item['id']]['type']],
                    'tname' => $tagInfo[$item['id']]['name'],
                    'score' => ((int)$item['score']) . '%',
                ];
            }

            $dataListItem = [
                'avatar' => $recodeDetails['avatar'],
                'nickname' => $recodeDetails['name'],
                'des' => sprintf("日%s 月%s 升%s", $recodeDetails['sun'], $recodeDetails['moon'], $recodeDetails['asc']),
                'score' => (int)$resultItem['probability'] . '%',
                'info_list' => $infoList,
                'recode_info' => [
                    [
                        'title' => '性别：',
                        'value' => $recodeDetails['type'] === 1 ? '男' : '女',
                    ], [
                        'title' => '出生时间：',
                        'value' => sprintf("%s.%02d.%02d %02d:%02d", $recodeDetails['year'], $recodeDetails['month'], $recodeDetails['day'], $recodeDetails['hour'], $recodeDetails['minute']),
                    ], [
                        'title' => '所在时区：',
                        'value' => $timezone,
                    ], [
                        'title' => '出生地点：',
                        'value' => $recodeDetails['birth_country'] . $recodeDetails['birth_province'] . $recodeDetails['birth_city'],
                    ], [
                        'title' => '经纬度：',
                        'value' => $longLat,
                    ], [
                        'title' => '现居地点：',
                        'value' => $recodeDetails['live_country'] . $recodeDetails['live_province'] . $recodeDetails['live_city'],
                    ],
                ],
            ];

            if (isset($dataListItem['recode_info'][3]['value']) && empty($dataListItem['recode_info'][3]['value']))
            {
                unset($dataListItem['recode_info'][3]);

                $dataListItem['recode_info'] = array_values($dataListItem['recode_info']);
            }

            $dataList[] = $dataListItem;
        }

        $resData = [
            'num' => $caseDetail['rid_num'],
            'status' => $caseDetail['status'],
            'rids' => $caseDetail['rids'],
            'order_id' => $caseDetail['order_num'],
            'case_id' => $id,
            'list' => $dataList,
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 我的理想型 方案 添加档案
     */
    public function myIdeaCaseAddRecode()
    {
        $id = input('id/d', 0);
        $rids = input('rids/s', '');

        if (!$id || empty($rids))
        {
            return show(config('code.error'), '请求异常');
        }

        $relationAnalysisIdeaModel = new Zl1RelationAnalysisIdea();

        $caseDetail = $relationAnalysisIdeaModel->getInfoById($id, ['id', 'uid', 'rids', 'rid_num', 'tag_info', 'order_num']);

        if (!$caseDetail || $caseDetail['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，理想型方案不存在～');
        }

        if ($caseDetail['rid_num'] >= 20)
        {
            return show(config('code.error'), '档案已经有20个了，不能添加更多了');
        }

        if (empty($rids))
        {
            return show(config('code.error'), '请选择要添加的档案');
        }

        $rids = array_map('intval', explode(',', $rids));

        $resRids = array_diff($rids, $caseDetail['rids']);

        if (empty($resRids))
        {
            return show(config('code.error'), '请选择要添加的档案');
        }

        $recodeModel = new \app\common\cachemodel\Recode();
        foreach ($resRids as $ridItem)
        {
            $recode = $recodeModel->getInfoById($ridItem);
            if (!$recode || $recode['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '选择的档案不存在');
            }
        }

        $ridsAll = array_merge($caseDetail['rids'], $resRids);
        $resNum = count($ridsAll);
        if ($resNum > 20)
        {
            return show(config('code.error'), '最多添加20个档案');
        }

        $ridsAllStr = implode(',', $ridsAll);

        // 更新方案信息
        $relationAnalysisIdeaModel->UpdateData($id, [
            'status' => 1,
            'rids' => $ridsAllStr,
        ]);

        // 发送重新计算队列
        Util::queuePush('relation_analysis_idea', [
            'id' => $id,
            'uid' => $this->user['id'],
            'rids' => $ridsAllStr,
            'tag_info' => json_encode($caseDetail['tag_info'], JSON_UNESCAPED_UNICODE),
            'is_update' => true
        ]);

        foreach ($resRids as $k => $ridItrm)
        {
            $resRids[$k] = (string)$ridItrm;
        }
        //  理想型档案新增成功    IdealLoverDetailUpdate    打点
        SensorsData::track($this->user['id'], true, 'IdealLoverDetailUpdate', [
            'case_id' => $id,    // 方案ID
            'order_id' => $caseDetail['order_num'],    // 订单ID
            'record_id_list' => $resRids,    // 入口名称
            'record_num' => $resNum,    // 新增后数量
        ]);

        return show(config('code.success'), '档案添加成功');
    }
}
